import { isVue2 } from 'vue-demi';

import vue3 from '@vitejs/plugin-vue';
import { resolve } from 'path';
import ScriptSetup from 'unplugin-vue2-script-setup/vite';
import { defineConfig } from 'vite';
import dtsPlugin from 'vite-plugin-dts';
import { createVuePlugin as vue2 } from 'vite-plugin-vue2';
import { createSvgPlugin } from 'vite-plugin-vue2-svg';
import svgLoader from 'vite-svg-loader';

export default defineConfig({
    resolve: {
        alias: [
            {
                find: 'vue-demi',
                replacement: resolve(
                    __dirname,
                    `node_modules/vue-demi/lib/${isVue2 ? 'v2' : 'v3'}/index.mjs`,
                ),
            },
        ],
        extensions: ['.ts', '.tsx', '.vue'],
    },
    build: {
        outDir: resolve(__dirname, `dist/${isVue2 ? 'v2' : 'v3'}`),
        emptyOutDir: false,
        lib: {
            entry: resolve(__dirname, 'src/index.ts'),
            formats: ['es', 'cjs', 'umd'],
            name: 'bookmark',
            fileName: (format) => `index.${format}.js`,
        },
        rollupOptions: {
            external: ['vue', '@vue/composition-api/dist/vue-composition-api.mjs'],
            output: {
                globals: {
                    vue: 'Vue',
                    '@vue/composition-api/dist/vue-composition-api.mjs': 'VueCompositionAPI',
                },
            },
        },
    },
    optimizeDeps: {
        exclude: ['vue-demi', 'vue', 'vue2', 'vue3'],
    },
    plugins: [
        ...(isVue2 ? [vue2(), createSvgPlugin(), ScriptSetup({})] : [vue3(), svgLoader()]),
        dtsPlugin({
            include: ['src/**'],
            tsconfigPath: resolve(__dirname, 'tsconfig.json'),
        }),
    ],
});
